package com.gxa.modules.pc.sys.usermanager.service.impl;

import com.gxa.common.utils.PageUtils;
import com.gxa.common.utils.Result;
import com.gxa.modules.pc.sys.usermanager.dto.MenuPcDto;
import com.gxa.modules.pc.sys.usermanager.dto.RolePcDto;
import com.gxa.modules.pc.sys.usermanager.dto.RoleSearchDto;
import com.gxa.modules.pc.sys.usermanager.mapper.RoleMenuPcMapper;
import com.gxa.modules.pc.sys.usermanager.mapper.RolePcMapper;
import com.gxa.modules.pc.sys.usermanager.service.RolePcService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName RolePcServiceImpl
 * @Description
 * @Author Mr.YUAN
 * @Date 2022/11/17 20:29
 */

@Service
public class RolePcServiceImpl implements RolePcService {

    @Autowired
    private RolePcMapper rolePcMapper;

    @Autowired
    private RoleMenuPcMapper roleMenuPcMapper;

    @Override
    public Result queryAll(RoleSearchDto roleSearchDto) {
        Integer pageNum = roleSearchDto.getPageNum();
        Integer pageSize = roleSearchDto.getPageSize();
        Integer pageNum1 = (pageNum-1)*pageSize;
        roleSearchDto.setPageNum(pageNum1);
        Integer count = rolePcMapper.count(roleSearchDto);
        List<RolePcDto> rolePcDtos = rolePcMapper.queryAll(roleSearchDto);
        PageUtils pageUtils = new PageUtils(rolePcDtos, count, pageSize, pageNum);
        return  new Result().ok(pageUtils);
    }


    @Override
    public void addRole(RolePcDto rolePcDto) {
        List<Integer> menus = rolePcDto.getMenus();
        rolePcMapper.insert(rolePcDto);
        for (int i = 0; i < menus.size(); i++) {
            roleMenuPcMapper.insertRMRelation(rolePcDto.getId(), menus.get(i));
        }
    }

//    @Override
//    public void delete(Integer id) {
//        rolePcMapper.deleteById(id);
//    }
@Override
public void delete(List<Integer> ids) {
    for (int i = 0; i < ids.size(); i++) {
        rolePcMapper.deleteById(ids.get(i));
        roleMenuPcMapper.deleteByROleId(ids.get(i));
    }
}

    @Override
    public void update(RolePcDto rolePcDto) {
        List<Integer> menus = rolePcDto.getMenus();
        //先查看是否修改：
        List<Integer> preMenus = roleMenuPcMapper.queryByRoleId(rolePcDto.getId());
        if (!menus.equals(preMenus)) {
            //修改了就更改数据库
            roleMenuPcMapper.deleteByROleId(rolePcDto.getId());
            for (int i = 0; i < menus.size(); i++) {
                roleMenuPcMapper.insertRMRelation(rolePcDto.getId(),menus.get(i));
            }
        }
        //未修改就
        rolePcMapper.updateRole(rolePcDto);
    }

    @Override
    public Result selectOne(Integer id) {
        RolePcDto rolePcDto = rolePcMapper.selectById(id);
        return new Result().ok(rolePcDto);
    }
}